//
//  YNFileMethod.m
//  xinhua
//
//  Created by fengyn on 15/11/12.
//  Copyright © 2015年 lexingsoft. All rights reserved.
//

#import "YNFileMethod.h"

@implementation YNFileMethod
///计算目录大小
+(unsigned long long)getDirectorySizeForPath:(NSString*)path
{
    NSFileManager*  fileManager = [[NSFileManager alloc] init];
    NSDirectoryEnumerator* e = [fileManager enumeratorAtPath:path];
    NSString *file;
    unsigned long long totalSize = 0;
    while ((file = [e nextObject]))
    {
        NSDictionary *attributes = [e fileAttributes];
        NSNumber *fileSize = [attributes objectForKey:NSFileSize];
        totalSize += [fileSize unsignedLongLongValue];
    }
    return totalSize;
}

///计算文件大小
+(unsigned long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

///获取文件扩展名
+(NSString *)fileType:(NSString *)fileName
{
    NSRange rang = [fileName rangeOfString:@"." options:NSBackwardsSearch];
    if (rang.location!=NSNotFound) {
        rang = NSMakeRange(rang.location+1, [fileName length]-rang.location-1);
        return [fileName substringWithRange:rang];
    }
    return nil;
}

///换算大小%.1fMB
+ (NSString *)convertSize1:(unsigned long long)sourceSize
{
    NSString *sSize = nil;
    float nSize = 0.0f;
    nSize = sourceSize/1024.0;
    sSize = [NSString stringWithFormat:@"%.1f KB",nSize];
    if (nSize<1) {
        sSize = [NSString stringWithFormat:@"%llu B",sourceSize];
        return sSize;
    }
    if (nSize>=1024) {
        nSize = nSize/1024.0;
        sSize = [NSString stringWithFormat:@"%.1f MB",nSize];
        if (nSize>=1024) {
            nSize = nSize/1024.0;
            sSize = [NSString stringWithFormat:@"%.1f GB",nSize];
            if (nSize>=1024) {
                nSize = nSize/1024.0;
                sSize = [NSString stringWithFormat:@"%.1f TB",nSize];
            }
        }
    }
    return sSize;
}

///换算大小%.2fMB
+ (NSString *)convertSize:(unsigned long long)sourceSize
{
    NSString *sSize = nil;
    float nSize = 0.0f;
    nSize = sourceSize/1024.0;
    sSize = [NSString stringWithFormat:@"%.2f KB",nSize];
    if (nSize<1) {
        sSize = [NSString stringWithFormat:@"%llu B",sourceSize];
        return sSize;
    }
    if (nSize>=1024) {
        nSize = nSize/1024.0;
        sSize = [NSString stringWithFormat:@"%.2f MB",nSize];
        if (nSize>=1024) {
            nSize = nSize/1024.0;
            sSize = [NSString stringWithFormat:@"%.2f GB",nSize];
            if (nSize>=1024) {
                nSize = nSize/1024.0;
                sSize = [NSString stringWithFormat:@"%.2f TB",nSize];
            }
        }
    }
    return sSize;
}
@end
